import time
from openpyxl import workbook
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


class AutoClub(object):
    def __init__(self):
        self.driver = webdriver.Chrome()
        # 创建一个数据表
        self.wb = workbook.Workbook()
        # 数据表的一个激活
        self.ws = self.wb.active
        # 添加一下数据表的表头
        self.ws.append(['token_id', '观看数', '点赞数', 'perunit_price', 'dollar_price', 'Last 7 days', 'Last 14 days', 'Last 30 days', 'Last 60 days', 'Last 90 days', 'Last year', 'All time'])

    def start(self):
        for page in range(4500, 5000):
            data_list = []
            # 确定页面的url
            url = f'https://opensea.io/assets/ethereum/0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d/{page}'
            # 开始访问
            self.driver.get(url)
            # 定义当前猴子的代号
            title = '#' + f'{page}'

            # 观看次数
            views = self.driver.find_element(By.XPATH, '//div[@class="sc-1xf18x6-0 sc-13kp31z-0 clHxmt"]').text
            # 喜欢次数
            favorites = self.driver.find_element(By.XPATH, '//button[@class="sc-ty1bh0-0 infdiL sc-1xf18x6-0 sc-13kp31z-0 clHxmt kaWAoE"]').text
            # 这里加判断
            price_name = self.driver.find_elements(By.XPATH, '//img[@alt="ETH"]|//img[@alt="WETH"]|//img[@alt="USDC"]')
            time.sleep(2)
            if len(price_name) == 1:
                if price_name[0].get_attribute('alt') == 'ETH':
                    # eth价格
                    perunit_price = self.driver.find_element(By.XPATH, '//div[@class="sc-7qr9y8-0 iUvoJs Price--amount"]').text
                else:
                    perunit_price = None
            else:
                perunit_price = None
            data_list.extend([title, views[11:-6], favorites[9:-10], perunit_price])
            # $价格
            dollar_price = self.driver.find_elements(By.XPATH, '//div[@class="sc-7qr9y8-0 iUvoJs Price--fiat-amount Price--fiat-amount-secondary"]')
            if len(dollar_price) != 0:
                dollar_price = dollar_price[0].text
                data_list.append(dollar_price[1:-1])
                print('================================')
                print(title)
                print(views[11:-6])
                print(favorites[9:-10])
                print(perunit_price)
                print(dollar_price[1:-1])
            else:
                dollar_price = None
                data_list.append(dollar_price)
                print('================================')
                print(title)
                print(views[11:-6])
                print(favorites[9:-10])
                print(perunit_price)
                print(dollar_price)
            # 爬取不同时间段的avg.time
            for date in range(1, 8):
                try:
                    # 点击选项框
                    self.driver.find_element(By.XPATH, '//*[@id="Body assets-item-timeline"]/div/div/div/div[1]/div[1]/div/div/div/i').click()
                    # time.sleep(1.5)
                    # 点击选项
                    self.driver.find_element(By.XPATH, f'//*[@id="Body assets-item-timeline"]/div/div/div/div[1]/div/div/div[2]//ul/li[{date}]').click()
                    # time.sleep(1.5)
                    # 等待折线图的加载
                    try:
                        # 等待事件 -- 怕网速慢
                        wait = WebDriverWait(self.driver, 30)  # 参数1：浏览器对象 参数2：时间（秒）
                        # 等待某元素出现 presence_of_element_located()传入的参数格式是一个元组
                        wait.until(EC.presence_of_element_located((By.XPATH, '//div[@class="sc-dy59cl-0 eXnWvj Image--isImageLoaded Image--isImageLoaderVisible PriceHistory--no-data-img"]/img|//div[@class="recharts-wrapper"]')))
                        # WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.XPATH, '//div[@class="sc-dy59cl-0 eXnWvj Image--isImageLoaded Image--isImageLoaderVisible PriceHistory--no-data-img"]/img|//div[@class="recharts-wrapper"]')))
                    except:
                        self.driver.refresh()
                except TimeoutError as te:
                    # print(te)
                    # 点击选项框
                    self.driver.find_element(By.XPATH, '//*[@id="Body assets-item-timeline"]/div/div/div/div[1]/div[1]/div/div/div/i').click()
                    time.sleep(2)
                    # 点击选项
                    self.driver.find_element(By.XPATH, f'//*[@id="Body assets-item-timeline"]/div/div/div/div[1]/div/div/div[2]//ul/li[{date}]').click()
                    time.sleep(4)
                finally:
                    try:
                        # 获取数据折线图的的提示信息
                        img_text = self.driver.find_elements(By.XPATH, '//div[@class="PriceHistory--no-data-text"]')
                        # 如果没有数据，结果为空，如有有数据，就展示所搜集的结果
                        if len(img_text) >= 1:
                            print('没有记录')
                            data_list.append(None)
                        else:
                            print('有记录')
                            avg_price = self.driver.find_element(By.XPATH, '//p[@class="sc-1xf18x6-0 sc-1w94ul3-0 iUhqVy doEVTy"]').text[1:]
                            print(f'记录的平均值值为{avg_price}')
                            data_list.append(f'{avg_price}')
                    except:
                        # print(te)
                        # 点击选项框
                        self.driver.find_element(By.XPATH, '//*[@id="Body assets-item-timeline"]/div/div/div/div[1]/div[1]/div/div/div/i').click()
                        time.sleep(2)
                        # 点击选项
                        self.driver.find_element(By.XPATH, f'//*[@id="Body assets-item-timeline"]/div/div/div/div[1]/div/div/div[2]//ul/li[{date}]').click()
                        time.sleep(4)
                        # 获取数据折线图的的提示信息
                        img_text = self.driver.find_elements(By.XPATH, '//div[@class="PriceHistory--no-data-text"]')
                        # 如果没有数据，结果为空，如有有数据，就展示所搜集的结果
                        if len(img_text) >= 1:
                            print('没有记录')
                            data_list.append(None)
                        else:
                            print('有记录')
                            avg_price = self.driver.find_element(By.XPATH, '//p[@class="sc-1xf18x6-0 sc-1w94ul3-0 iUhqVy doEVTy"]').text[1:]
                            print(f'记录的平均值值为{avg_price}')
                            data_list.append(f'{avg_price}')

            # time.sleep(10)
            self.ws.append(data_list)
            self.wb.save(f'monkeys数据2.xlsx')
            print('该数据已加载')
            print(data_list)
            print('================================')
        # 打印提示信息
        print('所有事件处理完成')
        # 关闭自动化
        self.driver.close()


if __name__ == '__main__':
    a = AutoClub()
    a.start()
